﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace PUBCOM
{
    public class XMLtoLIST
    {
        /// <summary> 
        /// 将简单的xml字符串转换成为LIST 
        /// </summary> 
        /// <typeparam name="T">类型，仅仅支持int/long/datetime/string/double/decimal/object</typeparam> 
        /// <param name="xml"></param> 
        /// <returns></returns> 
        /// <remarks></remarks> 
        public static List<T> xmlToList<T>(string xml)
        {
            Type tp = typeof(T);
            List<T> list = new List<T>();
            if (xml == null || string.IsNullOrEmpty(xml))
            {
                return list;
            }
            try
            {
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.LoadXml(xml);
                if (tp == typeof(string) | tp == typeof(int) | tp == typeof(long) | tp == typeof(DateTime) | tp == typeof(double) | tp == typeof(decimal))
                {
                    System.Xml.XmlNodeList nl = doc.SelectNodes("/SRMRequestOfDATA/PRIVATEKEY/INPUT");
                    if (nl.Count == 0)
                    {
                        return list;
                    }
                    else
                    {
                        foreach (System.Xml.XmlNode node in nl)
                        {
                            if (tp == typeof(string)) { list.Add((T)(object)Convert.ToString(node.InnerText)); }

                            else if (tp == typeof(int)) { list.Add((T)(object)Convert.ToInt32(node.InnerText)); }

                            else if (tp == typeof(long)) { list.Add((T)(object)Convert.ToInt64(node.InnerText)); }

                            else if (tp == typeof(DateTime)) { list.Add((T)(object)Convert.ToDateTime(node.InnerText)); }

                            else if (tp == typeof(double)) { list.Add((T)(object)Convert.ToDouble(node.InnerText)); }

                            else if (tp == typeof(decimal)) { list.Add((T)(object)Convert.ToDecimal(node.InnerText)); }

                            else { list.Add((T)(object)node.InnerText); }
                        }
                        return list;
                    }
                }
                else
                {
                    //如果是自定义类型就需要反序列化了 
                    System.Xml.XmlNodeList nl = doc.SelectNodes("/SRMRequestOfDATA/PRIVATEKEY/INPUT/DATA/" /*+ typeof(T).Name*/);
                    if (nl.Count == 0)
                    {
                        return list;
                    }
                    else
                    {
                        foreach (System.Xml.XmlNode node in nl)
                        {
                            list.Add(XMLToObject<T>(node.OuterXml));
                        }
                        return list;
                    }
                }
            }

            catch (XmlException ex)

            {

                throw new ArgumentException("不是有效的XML字符串", "xml");

            }
            catch (InvalidCastException e)
            {
                throw new ArgumentException("指定的数据类型不匹配", "T");
            }
            catch (Exception exx)
            {
                throw exx;
            }
        }
        /// <summary> 
        /// 将List转化为xml字符串 
        /// </summary> 
        /// <typeparam name="T">类型，仅仅支持int/long/datetime/string/double/decimal/object</typeparam> 
        /// <param name="list"></param> 
        /// <returns></returns> 
        /// <remarks></remarks> 
        public static string listToXml<T>(List<T> list)
        {
            Type tp = typeof(T);
            string xml = "<root>";
            if (tp == typeof(string) | tp == typeof(int) | tp == typeof(long) | tp == typeof(DateTime) | tp == typeof(double) | tp == typeof(decimal))
            {
                foreach (T obj in list)
                {
                    xml = xml + "<item>" + obj.ToString() + "</item>";
                }
            }
            else
            {
                xml = xml + "<items>";
                foreach (T obj in list)
                {
                    xml = xml + ObjectToXML<T>(obj);
                }
                xml = xml + "</items>";
            }
            xml = xml + "</root>";
            return xml;
        }

        #region 序列化xml/反序列化 

        /// <summary> 
        /// 对象序列化为XML 
        /// </summary> 
        /// <typeparam name="T"></typeparam> 
        /// <param name="obj"></param> 
        /// <param name="encoding"></param> 
        /// <returns></returns> 
        /// <remarks></remarks> 

        public static string ObjectToXML<T>(T obj, System.Text.Encoding encoding)
        {

            XmlSerializer ser = new XmlSerializer(obj.GetType());

            Encoding utf8EncodingWithNoByteOrderMark = new UTF8Encoding(false);

            using (MemoryStream mem = new MemoryStream())

            {

                XmlWriterSettings settings = new XmlWriterSettings

                {

                    OmitXmlDeclaration = true,

                    Encoding = utf8EncodingWithNoByteOrderMark

                };

                using (XmlWriter XmlWriter = XmlWriter.Create(mem, settings))

                {

                    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

                    ns.Add("", "");

                    ser.Serialize(XmlWriter, obj, ns);

                    return encoding.GetString(mem.ToArray());

                }

            }

        }

        /// <summary> 
        /// 对象序列化为xml 
        /// </summary> 
        /// <typeparam name="T"></typeparam> 
        /// <param name="obj"></param> 
        /// <returns></returns> 
        /// <remarks></remarks> 
        public static string ObjectToXML<T>(T obj)
        {
            return ObjectToXML<T>(obj, Encoding.UTF8);
        }

        /// <summary> 
        /// xml反序列化为对象 
        /// </summary> 
        /// <typeparam name="T"></typeparam> 
        /// <param name="source"></param> 
        /// <param name="encoding"></param> 
        /// <returns></returns> 
        /// <remarks></remarks> 
        public static T XMLToObject<T>(string source, Encoding encoding)
        {
            XmlSerializer mySerializer = new XmlSerializer(typeof(T));
            using (MemoryStream Stream = new MemoryStream(encoding.GetBytes(source)))
            {
                return (T)mySerializer.Deserialize(Stream);
            }
        }

        public static T XMLToObject<T>(string source)      
        {
            return XMLToObject<T>(source, Encoding.UTF8);
        }
        #endregion

    }

    public class XmlUtility
    {
        /// <summary>
         /// 将自定义对象序列化为XML字符串
         /// </summary>
         /// <param name="myObject">自定义对象实体</param>
         /// <returns>序列化后的XML字符串</returns>
        public static string SerializeToXml<T>(T myObject)
         {
             if (myObject != null)
             {
                 XmlSerializer xs = new XmlSerializer(typeof(T));
 
                 MemoryStream stream = new MemoryStream();
                 XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
                 writer.Formatting = Formatting.None;//缩进
                 xs.Serialize(writer, myObject);
 
                 stream.Position = 0;
                 StringBuilder sb = new StringBuilder();
                 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                 {
                     string line;
                     while ((line = reader.ReadLine()) != null)
                     {
                         sb.Append(line);
                     }
                    reader.Close();
                }
                 writer.Close();
                 return sb.ToString();
             }
             return string.Empty;
         }
 
         /// <summary>
         /// 将XML字符串反序列化为对象
         /// </summary>
         /// <typeparam name="T">对象类型</typeparam>
         /// <param name="xml">XML字符</param>
         /// <returns></returns>
         public static T DeserializeToObject<T>(string xml)
        {
             T myObject;
             XmlSerializer serializer = new XmlSerializer(typeof(T));
             StringReader reader = new StringReader(xml);
            myObject = (T)serializer.Deserialize(reader);
             reader.Close();
             return myObject;
         }
     }


    public class OrderGoodInfo
    {
        private int _type;
        private int _goodid;
        private int _number;
        private string _name;
        private decimal _price;
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }


        public int Type
        {
            get { return _type; }
            set { _type = value; }
        }

        public int GoodId
        {
            get { return _goodid; }
            set { _goodid = value; }
        }

        public int Number
        {
            get { return _number; }
            set { _number = value; }
        }

        public decimal Price
        {
            get { return _price; }
            set { _price = value; }
        }
    }

    public class XMLtoLIST2
    {
        #region 实体类，XML互操作
        /// <summary>
        /// 实体类序列化成xml
        /// </summary>
        /// <param name="enitities">The enitities.</param>
        /// <param name="headtag">The headtag.</param>
        /// <returns></returns>
        public static string ObjListToXml<T>(List<T> enitities, string headtag)
        {
            StringBuilder sb = new StringBuilder();
            PropertyInfo[] propinfos = null;
            sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            sb.AppendLine("<" + headtag + ">");
            foreach (T obj in enitities)
            {
                //初始化propertyinfo
                if (propinfos == null)
                {
                    Type objtype = obj.GetType();
                    propinfos = objtype.GetProperties();
                }

                sb.AppendLine("<item>");
                foreach (PropertyInfo propinfo in propinfos)
                {
                    sb.Append("<");
                    sb.Append(propinfo.Name);
                    sb.Append(">");
                    sb.Append(propinfo.GetValue(obj, null));
                    sb.Append("</");
                    sb.Append(propinfo.Name);
                    sb.AppendLine(">");
                }
                sb.AppendLine("</item>");
            }
            sb.AppendLine("</" + headtag + ">");
            return sb.ToString();
        }

        /// <summary>
        /// 使用XML初始化实体类容器
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="typename">The typename.</param>
        /// <param name="xml">The XML.</param>
        /// <param name="headtag">The headtag.</param>
        /// <returns></returns>
        public static List<T> XmlToObjList<T>(string xml, string headtag)
            where T : new()
        {
            List<T> list = new List<T>();
            XmlDocument doc = new XmlDocument();
            PropertyInfo[] propinfos = null;
            doc.LoadXml(xml);
            XmlNodeList nodelist = doc.SelectNodes("/" + headtag + "/item");
            foreach (XmlNode node in nodelist)
            {
                T entity = new T();
                //初始化propertyinfo
                if (propinfos == null)
                {
                    Type objtype = entity.GetType();
                    propinfos = objtype.GetProperties();
                }
                //填充entity类的属性
                foreach (PropertyInfo propinfo in propinfos)
                {
                    XmlNode cnode = node.SelectSingleNode(propinfo.Name);
                    string v = cnode.InnerText;
                    if (v != null)
                        propinfo.SetValue(entity, Convert.ChangeType(v, propinfo.PropertyType), null);
                }
                list.Add(entity);
            }
            return list;
        }

        #endregion
    }
//使用如下：

//protected void Page_Load(object sender, EventArgs e)
//{
//    OrderGoodInfo good1 = new OrderGoodInfo();
//    good1.GoodId = 1;
//    good1.Number = 1;
//    good1.Price = 100;
//    good1.Type = 1;

//    OrderGoodInfo good2 = new OrderGoodInfo();
//    good2.GoodId = 2;
//    good2.Number = 2;
//    good2.Price = 200;
//    good2.Type = 2;

//    List<OrderGoodInfo> list = new List<OrderGoodInfo>();
//    list.Add(good1);
//    list.Add(good2);

//    string xmlstr = XmlHelper.ObjListToXml(list, "goods");
//    Response.Write(xmlstr);

//    List<OrderGoodInfo> nlist = XmlHelper.XmlToObjList<OrderGoodInfo>(xmlstr, "goods");

//    Response.Write(XmlHelper.ObjListToXml(nlist, "goods"));
//}


}
